import MySQLdb
import sys
import time

# usage example: $python importer/ids.py pwd sample_ori_ids sample/IDS_log.txt

DEBUG = 2

YEAR = 2011 # omitted in the log, so append it

if __name__ == '__main__':
    db = MySQLdb.connect(host="rome.cs.vt.edu", port=5801, user="fusetester", passwd=sys.argv[1], db="fusebox")

    tablename = sys.argv[2]
    filename = sys.argv[3]
    hfile = open(filename)

    counter = 1
    for block in hfile.read().split('\n\n'):
        if block != '':
            lines = block.split('\n')

            if DEBUG >= 3:
                print '#### LINES ####'
                print lines

            rule = lines[0][6:-5]
            ruleN, ruleV = rule.split('] ') # rule No. and rule violation discription
            if len(ruleV) > 1024 and DEBUG >= 1:
                print 'Warning: rule discription is out of space!'

            # notice: there is a ' ' at the end of lines[1]
            cate, priority = lines[1][17:-2].split('] [Priority: ')
            if len(cate) > 256 and DEBUG >= 1:
                print 'Warning: category is out of space!'

            timestr, source, tmpnone, dest = lines[2].split()
            timestr = timestr.split('.')[0] # get rid of milliseconds
            timestr = str(YEAR) + '/' + timestr # append year to strip
            unixdate = int(time.mktime(time.strptime(timestr, "%Y/%m/%d-%H:%M:%S")))
            sourceip, sourceport = source.split(':')
            destip, destport = dest.split(':')

            db.query('INSERT INTO %s (rulenum, ruledis, cate, priority, date, sourceip, sourceport, destip, destport) VALUES ("%s", "%s", "%s", %s, %d, "%s", %s, "%s", %s)' % (tablename, ruleN, ruleV, cate, priority, unixdate, sourceip, sourceport, destip, destport))

            if DEBUG >= 2:
                print '#### END %d ####' % (counter)
            counter += 1

    db.close()

